<template>
  <div class="relative">
    <div v-if="content || $slots.headerContent || title || getHeaderSlots.length" ref="headerRef">
      <PageHeader :ghost="ghost" :title="title" :class="headerClass" v-bind="omit($attrs, 'class')">
        <template #default>
          <template v-if="content">
            {{ content }}
          </template>
          <slot name="headerContent" v-else></slot>
        </template>
        <template #[item]="data" v-for="item in getHeaderSlots">
          <slot :name="item" v-bind="data || {}"></slot>
        </template>
      </PageHeader>
    </div>

    <div :class="contentClass" :style="contentStyle" class="h-full p-4">
      <slot></slot>
    </div>

    <div v-if="$slots.footer" ref="footerRef" :class="footerClass">
      <slot name="footer"></slot>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { computed, nextTick, onMounted, ref, type StyleValue, useTemplateRef, useSlots } from 'vue';
  import { omit } from 'lodash-es';
  import { usePageContext } from '/@/hooks/component/usePageContext';
  import { PageHeader } from 'ant-design-vue';

  defineOptions({
    name: 'Page',
  });
  interface Props {
    title?: string;
    contentClass?: string;
    contentFullHeight?: boolean;
    fixedHeight?: boolean;
    headerClass?: string;
    footerClass?: string;
    ghost?: boolean;
    content?: string;
  }
  const props = defineProps<Props>();

  const headerHeight = ref(0);
  const footerHeight = ref(0);

  const headerRef = useTemplateRef<HTMLDivElement>('headerRef');
  const footerRef = useTemplateRef<HTMLDivElement>('footerRef');
  const slots = useSlots();
  const { contentHeight } = usePageContext();

  const getHeaderSlots = computed(() => {
    return Object.keys(omit(slots, 'default', 'footer', 'headerContent'));
  });

  const contentStyle = computed<StyleValue>(() => {
    let { contentFullHeight, fixedHeight } = props;
    if (!contentFullHeight && !fixedHeight) {
      return {};
    }
    let height = contentHeight.value - headerHeight.value + 'px';
    return {
      'min-height': height,
      ...(fixedHeight ? { height } : {}),
      overflowY: fixedHeight ? 'auto' : 'unset',
    };
  });

  async function calcContentHeight() {
    if (!props.contentFullHeight && !props.fixedHeight) {
      return;
    }
    await nextTick();
    headerHeight.value = headerRef.value?.offsetHeight || 0;
    footerHeight.value = footerRef.value?.offsetHeight || 0;
  }

  onMounted(() => {
    calcContentHeight();
  });
</script>
